package com.blacktea.magicapi.provider;

import com.blacktea.magicapi.base.BaseConstant;
import com.blacktea.magicapi.policy.exitvalue.ExitValuePolicyContext;
import org.ssssssss.magicapi.model.Constants;
import org.ssssssss.magicapi.model.JsonBean;
import org.ssssssss.magicapi.model.RequestEntity;
import org.ssssssss.magicapi.provider.ResultProvider;
import org.ssssssss.script.runtime.ExitValue;

/**
 * @description: 自定义JSON结果
 * @author: black tea
 * @date: 2021/12/31 9:14
 */
public class CustomJsonValueProvider implements ResultProvider {

    @Override
    public Object buildResult(RequestEntity requestEntity, Object data) {
        if (data instanceof ExitValue) {
            ExitValue exitValue = (ExitValue)data;
            Object[] values = exitValue.getValues();
            ExitValuePolicyContext context = ExitValuePolicyContext.of(values);
            return context.execute(values,requestEntity,this);
        } else {
            return this.buildResult(requestEntity, Constants.RESPONSE_CODE_SUCCESS, BaseConstant.RESULT_SUCCESS_MESSAGE, data);
        }
    }

    @Override
    public Object buildResult(RequestEntity requestEntity, int code, String message, Object data) {
        long timestamp = System.currentTimeMillis();
        return new JsonBean<>(code, message, data, (int) (timestamp - requestEntity.getRequestTime()));
    }

}
